/*
 * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version
 * 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for
 * the specific language governing permissions and limitations under the License.
 */

package jmine.tec.test.junit.runner.formatter;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import jmine.tec.test.junit.runner.ConsoleTestRunner;
import jmine.tec.test.junit.runner.JUnitTest;
import jmine.tec.test.junit.runner.JUnitVersionHelper;
import junit.framework.AssertionFailedError;
import junit.framework.Test;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.util.DOMElementWriter;
import org.apache.tools.ant.util.DateUtils;
import org.apache.tools.ant.util.FileUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

/**
 * Prints XML output of the test to a specified Writer.
 */

public class XMLJUnitResultFormatter implements JUnitResultFormatter {

    private static final double ONE_SECOND = 1000.0;

    /** constant for unnnamed testsuites/cases */
    private static final String UNKNOWN = "unknown";

    /**
     * @return create new {@link DocumentBuilder}
     */
    private static DocumentBuilder getDocumentBuilder() {
        try {
            return DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (Exception exc) {
            throw new ExceptionInInitializerError(exc);
        }
    }

    /**
     * The XML document.
     */
    private Document doc;

    /**
     * The wrapper for the whole testsuite.
     */
    private Element rootElement;

    /**
     * Element for the current test.
     */
    private Hashtable<Test, Element> testElements = new Hashtable<Test, Element>();

    /**
     * tests that failed.
     */
    private Hashtable<Test, Test> failedTests = new Hashtable<Test, Test>();

    /**
     * Timing helper.
     */
    private Hashtable<Test, Long> testStarts = new Hashtable<Test, Long>();

    /**
     * Where to write the log to.
     */
    private OutputStream out;

    /** No arg constructor. */
    public XMLJUnitResultFormatter() {
    }

    /** {@inheritDoc}. */
    public void setOutput(OutputStream output) {
        this.out = output;
    }

    /** {@inheritDoc}. */
    public void setSystemOutput(String systemOutput) {
        this.formatOutput(XMLConstants.SYSTEM_OUT, systemOutput);
    }

    /** {@inheritDoc}. */
    public void setSystemError(String systemError) {
        this.formatOutput(XMLConstants.SYSTEM_ERR, systemError);
    }

    /**
     * The whole testsuite started.
     * 
     * @param suite the testsuite.
     */
    public void startTestSuite(JUnitTest suite) {
        this.doc = getDocumentBuilder().newDocument();
        this.rootElement = this.doc.createElement(XMLConstants.TESTSUITE);
        String n = suite.getName();
        this.rootElement.setAttribute(XMLConstants.ATTR_NAME, n == null ? UNKNOWN : n);

        // add the timestamp
        final String timestamp = DateUtils.format(new Date(), DateUtils.ISO8601_DATETIME_PATTERN);
        this.rootElement.setAttribute(XMLConstants.TIMESTAMP, timestamp);
        // and the hostname.
        this.rootElement.setAttribute(XMLConstants.HOSTNAME, this.getHostname());

        // Output properties
        Element propsElement = this.doc.createElement(XMLConstants.PROPERTIES);
        this.rootElement.appendChild(propsElement);
        Properties props = suite.getProperties();
        if (props != null) {
            Enumeration e = props.propertyNames();
            while (e.hasMoreElements()) {
                String name = (String) e.nextElement();
                Element propElement = this.doc.createElement(XMLConstants.PROPERTY);
                propElement.setAttribute(XMLConstants.ATTR_NAME, name);
                propElement.setAttribute(XMLConstants.ATTR_VALUE, props.getProperty(name));
                propsElement.appendChild(propElement);
            }
        }
    }

    /**
     * get the local hostname
     * 
     * @return the name of the local host, or "localhost" if we cannot work it out
     */
    private String getHostname() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            return "localhost";
        }
    }

    /**
     * The whole testsuite ended.
     * 
     * @param suite the testsuite.
     */
    public void endTestSuite(JUnitTest suite) {
        this.rootElement.setAttribute(XMLConstants.ATTR_TESTS, "" + suite.runCount());
        this.rootElement.setAttribute(XMLConstants.ATTR_FAILURES, "" + suite.failureCount());
        this.rootElement.setAttribute(XMLConstants.ATTR_ERRORS, "" + suite.errorCount());
        this.rootElement.setAttribute(XMLConstants.ATTR_TIME, "" + (suite.getRunTime() / ONE_SECOND));
        if (this.out != null) {
            Writer wri = null;
            try {
                wri = new BufferedWriter(new OutputStreamWriter(this.out, "UTF8"));
                wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
                (new DOMElementWriter()).write(this.rootElement, wri, 0, "  ");
            } catch (IOException exc) {
                throw new BuildException("Unable to write log file", exc);
            } finally {
                if (wri != null) {
                    try {
                        wri.flush();
                    } catch (IOException ex) {
                        // ignore
                    }
                }
                if (this.out != System.out && this.out != System.err) {
                    FileUtils.close(wri);
                }
            }
        }
    }

    /**
     * Interface TestListener.
     * <p>
     * A new Test is started.
     * 
     * @param t the test.
     */
    public void startTest(Test t) {
        this.testStarts.put(t, new Long(System.currentTimeMillis()));
    }

    /**
     * Interface TestListener.
     * <p>
     * A Test is finished.
     * 
     * @param test the test.
     */
    public void endTest(Test test) {
        // Fix for bug #5637 - if a junit.extensions.TestSetup is
        // used and throws an exception during setUp then startTest
        // would never have been called
        if (!this.testStarts.containsKey(test)) {
            this.startTest(test);
        }

        Element currentTest = null;
        if (!this.failedTests.containsKey(test)) {
            currentTest = this.doc.createElement(XMLConstants.TESTCASE);
            String n = JUnitVersionHelper.getTestCaseName(test);
            currentTest.setAttribute(XMLConstants.ATTR_NAME, n == null ? UNKNOWN : n);
            // a TestSuite can contain Tests from multiple classes,
            // even tests with the same name - disambiguate them.
            currentTest.setAttribute(XMLConstants.ATTR_CLASSNAME, JUnitVersionHelper.getTestCaseClassName(test));
            this.rootElement.appendChild(currentTest);
            this.testElements.put(test, currentTest);
        } else {
            currentTest = (Element) this.testElements.get(test);
        }

        Long l = (Long) this.testStarts.get(test);
        currentTest.setAttribute(XMLConstants.ATTR_TIME, "" + ((System.currentTimeMillis() - l.longValue()) / ONE_SECOND));
    }

    /**
     * Interface TestListener for JUnit &lt;= 3.4.
     * <p>
     * A Test failed.
     * 
     * @param test the test.
     * @param t the exception.
     */
    public void addFailure(Test test, Throwable t) {
        this.formatError(XMLConstants.FAILURE, test, t);
    }

    /**
     * Interface TestListener for JUnit &gt; 3.4.
     * <p>
     * A Test failed.
     * 
     * @param test the test.
     * @param t the assertion.
     */
    public void addFailure(Test test, AssertionFailedError t) {
        this.addFailure(test, (Throwable) t);
    }

    /**
     * Interface TestListener.
     * <p>
     * An error occurred while running the test.
     * 
     * @param test the test.
     * @param t the error.
     */
    public void addError(Test test, Throwable t) {
        this.formatError(XMLConstants.ERROR, test, t);
    }

    /**
     * Format error.
     * 
     * @param type type
     * @param test test
     * @param t {@link Throwable}
     */
    private void formatError(String type, Test test, Throwable t) {
        if (test != null) {
            this.endTest(test);
            this.failedTests.put(test, test);
        }

        Element nested = this.doc.createElement(type);
        Element currentTest = null;
        if (test != null) {
            currentTest = (Element) this.testElements.get(test);
        } else {
            currentTest = this.rootElement;
        }

        currentTest.appendChild(nested);

        String message = t.getMessage();
        if (message != null && message.length() > 0) {
            nested.setAttribute(XMLConstants.ATTR_MESSAGE, t.getMessage());
        }
        nested.setAttribute(XMLConstants.ATTR_TYPE, t.getClass().getName());

        String strace = ConsoleTestRunner.getFilteredTrace(t);
        Text trace = this.doc.createTextNode(strace);
        nested.appendChild(trace);
    }

    /**
     * Format output.
     * 
     * @param type type
     * @param output output
     */
    private void formatOutput(String type, String output) {
        Element nested = this.doc.createElement(type);
        this.rootElement.appendChild(nested);
        nested.appendChild(this.doc.createCDATASection(output));
    }

}
